/**
 * Created by liuqingxia on 2016/3/29.
 */

/**
 * main入口
 */
$(document).ready(function () {
    adjustRowWidth();
    clickClusterCard();
    flushClusterBoards(1000);
});

var cachedAllClusterResults;

function adjustRowWidth() {
    //var row = $("#cluster-row-1");
    //var width = row.width();
    //console.log("当前row的长度为：" + width);
    //var colWidth = (width - 450 * 3) / 2 - 19;
    //console.log("调整占位，colWidth:" + colWidth);
    //
    //$.each($(".placeHolder-col"), function () {
    //    $(this).width(colWidth);
    //});
}

/**
 * 点击集群名片
 */
function clickClusterCard() {
    $(document).on("click", ".moreClusterStatus-btn", function () {
        var clusterId = $(this).parent().parent().find("span.clusterId").html();
        var params = "?clusterId=" + $.trim(clusterId);
        console.log("查看集群信息，clusterId=" + clusterId);
        window.open(getUrlBySuffix("/tddl/cluster/hardware" + params));
    });
}

var intervalId;

/**
 * 刷新ClusterBoards
 * @param time
 */
function flushClusterBoards(time) {

    try {
        intervalId = self.setInterval("drawClusterBoards()", time);
    } catch (e) {
        console.log("刷新ClusterResultVO的Board时，发生异常,异常信息为：" + e.message);
        if (typeof intervalId != "undefined") {
            window.clearInterval(intervalId);
        }
    }

}

/**
 * 画ClusterBoards
 */
function drawClusterBoards() {
    var clusterResultVOs = getClusterResultVOs();
    renderClusterTemplate(clusterResultVOs, "cluster-board-template", "clusterBoards-div");
}

/**
 * 获取ClusterResultVO
 * @returns {*}
 */
function getClusterResultVOs() {
    var clusterResults;
    var params = {lastClusterResults: JSON.stringify(cachedAllClusterResults)};
    var url = getUrlBySuffix("/tddl/cluster/getAllClusterResults");
    try {
        $.postHttpSync(params, url, function (json) {
            if (json && json.success) {
                clusterResults = json['list'];
                cacheClusterResult(clusterResults);
            } else {
                console.log("获取ClusterResultVO失败，请查看服务器端日志");
            }
        })
    } catch (e) {
        console.log("获取ClusterResultVO时发生异常，异常信息为：" + e.message);
    }
    return clusterResults;
}

/**
 * 渲染模板
 * @param clusterResultVOs
 * @param templateId
 * @param contentId
 */
function renderClusterTemplate(clusterResultVOs, templateId, contentId) {
    var success = true;
    if (typeof clusterResultVOs == "undefined") {
        success = false;
    }
    var data = {
        success: success,
        rows: clusterResultVOs
    };
    var html = template(templateId, data);
    var contentEle = $("#" + contentId);
    contentEle.empty();
    contentEle.append(html);
}

/**
 * 缓存allClusterResults
 * @param allClusterResults
 */
function cacheClusterResult(allClusterResults) {
    cachedAllClusterResults = allClusterResults;
}

